package com.ssyc.student.activity;

import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.CanotSlidingViewpager;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.student.R;
import com.ssyc.student.bean.VocabularyInfo;
import com.ssyc.student.fragment.StudentVocabularyDetectionFragment;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--金牌金概念2--题型选择--词汇检测界面
 * Created by Administrator on 2018/5/14 0014.
 */

public class StudentVocabularyDetectionActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    //加载框
    private RelativeLayout rlLoading;

    //内容布局
    private LinearLayout llContent;

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //课程的LessonId在提交界面可能需要该值,页面传递过来
    private String lessonId;

    //gradeId
    private String gradeId;

    //返回
    private ImageView ivBack;
    //进度条
    private ZzHorizontalProgressBar pb;

    //显示进度条的文本
    private TextView tvPb;

    //可控制是否滚动的ViewPager
    private CanotSlidingViewpager vp;

    //用于记录Vp当前滑动的位置
    private int currPos;

    //用于记录Vp划过的最大位置的值
    private int maxPos;

    //填充Vp的Fragment集合
    private List<Fragment> mFragments;

    //Vp的适配器
    private VpCommonAdapter adapter;

    //Handler对象
    private Handler handler = new Handler();

    //用于保存做题的选择题目答案的Map,key为当前的位置,value为选择的答案
    public static Map<Integer, String> chooseAnswerMap;

    //用于保存用户答题的对错的Map,key为当前的位置,value为答题的状态值
    public static Map<Integer, Boolean> answerMap;

    //通知Acitvity进行ViewPager翻页的标识
    public static String VPSCOLL = "StudentVocabularyDetectionActivity.class";

    //静态代码块
    {
        //这里使用有序的Map来存放题目
        chooseAnswerMap = new LinkedHashMap<>();
        answerMap = new LinkedHashMap<>();

        //初始化记录时间的对象
        TimeCount.init();
    }

    //获取保存答题Map的方法
    public static Map<Integer, String> getChooseAnswerMap() {
        return chooseAnswerMap;
    }

    //获取保存答题正确或者错误Map的方法
    public static Map<Integer, Boolean> getAnswerMap() {
        return answerMap;
    }

    //用于上传服务器记录时间的id
    private String rowId;

    //重新提交的标识
    public static final int SHOWPOPWINDOW = 0x330;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_vocabulary_detection;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //获取Intent数据
        initIntent();

        //获取数据
        http();
    }


    /**
     * 初始化视图
     */
    public void initView() {

        rlLoading = findViewById(R.id.rl_loading_view);
        rlLoading.setVisibility(View.VISIBLE);
        llContent = findViewById(R.id.ll_content);
        llContent.setVisibility(View.INVISIBLE);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        pb = findViewById(R.id.pb);
        tvPb = findViewById(R.id.tv_pb);
        vp = findViewById(R.id.vp);
        //初次进入禁止右边滑动
        vp.setScrollble(false);
        //设置监听
        vp.addOnPageChangeListener(this);
    }


    /**
     * 获取Intent数据
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);
    }


    /**
     * 请求服务器数据
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "20");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lesson", "Lesson" + lessonId);
        map.put("examtype", "13");
        map.put("role", AccountUtils.getRole(this));

        HttpUtils.post(HttpAdress.TEXTPREPARE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                if (null != llContent) {
                    llContent.setVisibility(View.INVISIBLE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    if (null != rlLoading) {
                        rlLoading.setVisibility(View.GONE);
                    }
                    if (null != llContent) {
                        llContent.setVisibility(View.VISIBLE);
                    }
                    VocabularyInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, VocabularyInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    LogUtils.iTag("test", "返回的数据是" + info);

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            VocabularyInfo.DataBean data = info.getData();
                            if (null != data) {

                                //取出所有问题的集合
                                List<VocabularyInfo.DataBean.QuestionListBean> question_list = data.getQuestion_list();

                                if (null != question_list && question_list.size() != 0) {
                                    //初始化填充的Framgent
                                    initFragments(question_list);

                                    //设置Vp
                                    initVp();
                                }
                            }

                        } else {
                            //服务器返回异常状态码
                            UiUtils.Toast("服务器异常", false);
                            Log.i("test", "返回异常码是:" + info.getState());
                        }
                    }
                }
            }
        });

    }


    /**
     * 初始化Fragments的方法,需要在请求服务器后获取到数据后执行
     */
    private void initFragments(List<VocabularyInfo.DataBean.QuestionListBean> question_list) {
        if (null == question_list || question_list.size() == 0) {
            Log.i("test", "服务器返回的问题集合为空");
            return;
        }

        mFragments = new ArrayList<>();
        for (int i = 0; i < question_list.size(); i++) {

            mFragments.add(StudentVocabularyDetectionFragment.newInstance(question_list.get(i), i, lessonId, gradeId, GsonUtil.listToJson(question_list)));

            //保证每个选项的答案选项都有初始值
            chooseAnswerMap.put(i, "");

            //防止保存的答案和对应的序列号错误,提供初始值
            answerMap.put(i, false);
        }

        //设置默认进度条的值
        pb.setProgress((int) ((float) (1) / (float) (mFragments.size()) * 100));

        //设置当前展示的Vp的页码
        tvPb.setText("1/" + (mFragments.size()));
    }

    /**
     * 设置ViewPager的方法
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }


    /**
     * ViewPager的滚动监听事件
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        //记录当前滑动位置
        currPos = position;

        //复制vp滑动的最大位置值
        if (position > maxPos) {
            maxPos = position;
        }

        //根据当前位置来设置Vp是否可以向右滑动
        if (currPos < maxPos) {
            //如果当前位置小于Vp滑动过的最大位置,则可以右滑,否则不能右滑
            vp.setScrollble(true);
        } else {
            vp.setScrollble(false);
        }

        if (position != mFragments.size()) {
            //设置进度条的文本显示值
            tvPb.setText((position + 1) + "/" + (mFragments.size()));

            //同时需要设置进度条的值
            pb.setProgress((int) ((float) (currPos + 1) / (float) (mFragments.size()) * 100));
        }


        //如果当前位置是最后一个位置,发送消息给StudentVocabularyDetectionFragment
        if (currPos == mFragments.size() - 1) {
            BusInfo busInfo = new BusInfo();
            busInfo.setType(SHOWPOPWINDOW);
            EventBus.getDefault().post(busInfo);
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 页面控件的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        }
    }

    /**
     * 接受事件的方法
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        //通知ViewPager翻页
        if (null != busInfo && StudentVocabularyDetectionActivity.VPSCOLL.equals(busInfo.vpScoll)) {

            Log.i("test", "事件响应" + currPos);
            currPos += 1;
//            vp.setCurrentItem(currPos);
            //延迟300毫秒跳转页面
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    vp.setCurrentItem(currPos);
                }
            }, 50);
        } else if (null != busInfo && StudentVocabularyDetectionFragment.CLOSE == busInfo.getType()) {
            //关闭页面的事件
            finish();
        }
    }

    /**
     * 该生命周期内请求服务器记录初次进入的时间
     */
    @Override
    protected void onResume() {
        super.onResume();
        RecordTimeUtil.httpEnterTime(this, lessonId, gradeId, "13", new RecordTimeUtil.onRecordRowIdListener() {
            @Override
            public void recordRowId(String id, String en) {
                rowId = id;
            }
        });
    }


    /**
     * 考虑熄屏
     */
    @Override
    protected void onPause() {
        super.onPause();
        long time = System.currentTimeMillis() - TimeCount.newInstance().getLastTime();

        //计算总用时
        long totalTime = TimeCount.newInstance().getTotalTime() + time;

        //记录总用时
        TimeCount.newInstance().setTotalTime(totalTime);

        //上传服务器记录时间的接口
        RecordTimeUtil.httpExitTime(rowId, this);

    }

    /**
     * 考虑亮屏
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        //重置LastTime
        TimeCount.newInstance().setLastTime(System.currentTimeMillis());
    }


    /**
     * 生命周期中移除消息
     */
    @Override
    protected void onDestroy() {
        //取消Handler的任务
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }

}
